package org.top10.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.cyberneko.html.parsers.DOMParser;
import org.top10.collector.Collector;
import org.top10.dealor.FileDealor;
import org.top10.entity.CollectEntity;
import org.top10.entity.Video;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Nekohtml {

	protected  static Node getNodeByPattern(Node root, String tagName,
			Pattern p) {

		if (root.getNodeType() == Node.ELEMENT_NODE) {
			Element elmt = (Element) root;
			if (elmt.getTagName().equals("STYLE")
					|| elmt.getTagName().equals("SCRIPT"))
				return null;
			
			if (elmt.getNodeName().equalsIgnoreCase(tagName)
					&&(p==null|| p.matcher(elmt.getTextContent()).find())) {
				return root;
			}
		
			NodeList children = elmt.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				Node t = getNodeByPattern(children.item(i), tagName, p);
				if (t!=null)return t;
			}
		}
		return null;
	}
	protected  static Node getNodeByPattern(Node root, String tagName) {
			return getNodeByPattern(root,tagName ,null);
	
	}
	private static void getAllTagsByAParent(Node root,String tagName,List<Node>tags){
		if(root==null)return ;
		if(TOP10Global.isEmptyStr(tagName)||tags==null)
			throw new IllegalArgumentException("tagName or node is null");
		if (root.getNodeType() == Node.ELEMENT_NODE) {
			
			Element elmt = (Element) root;
			if (elmt.getTagName().equals("STYLE")
					|| elmt.getTagName().equals("SCRIPT"))
				return ;

			if (tagName.equalsIgnoreCase(root.getNodeName())) {
				tags.add(root);
			}
			NodeList children = elmt.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				getAllTagsByAParent(children.item(i),tagName,tags);
			}
		}
	}

	private static String getAttrValueByTag(Node node,String attr) {
		if(node==null)return null;
		if(TOP10Global.isEmptyStr(attr))
			throw new IllegalArgumentException("attr is null");
		if (node.getNodeType() == Node.ELEMENT_NODE) {
				NamedNodeMap attrs = node.getAttributes();
				for (int i = 0; i < attrs.getLength(); i++) {
					if (attr.equalsIgnoreCase(attrs.item(i).getNodeName())) {
						return attrs.item(i).getNodeValue();// 在DOM树中，属性是一个结点。
					}
				}
		}
		return null;
	}

	public static List<CollectEntity> parse(Document doc) {

		List<Video> list=new ArrayList<Video>();
		Node body = doc.getElementsByTagName("BODY").item(0);
		Pattern p = Pattern.compile("电影\\s*TOP10", Pattern.MULTILINE);
		Node node=getNodeByPattern(body, "h2", p);
		List<Node>lis=new ArrayList<Node>();
		getAllTagsByAParent(node.getParentNode(),"li",lis);
		if(lis!=null){
			for(int i=0;i<lis.size();i++){
				Video v=buildVideo(lis.get(i),i+1);
				System.out.println(v.toString());
				list.add(v);
			}
		}
		return null;
	}
	private static Video buildVideo(Node li,int rank){
		Video v=new Video();
		 String DESC_PRE="http://data.movie.xunlei.com/movie/";
		List<Node>as=new ArrayList<Node>();
		v.setRank(rank);
		getAllTagsByAParent(li,"a",as);
		if(as.size()>=2){
			Node a1=as.get(0);
			Node a2=as.get(1);
			String url=getAttrValueByTag(a1,"href");
			v.setPlayUrl(url);
			v.setDescUrl(getAttrValueByTag(a2,"href"));
			if(rank==1){
				v.setName(a2.getTextContent());
			}else{
				v.setName(a1.getTextContent());
			}
			getAllTagsByAParent(li,"strong",as);
			v.setPoint(as.get(as.size()-1).getTextContent());
			
		}
		return v;
	}
	public static void main(String[] args) throws Exception {
		// 生成html parser
		DOMParser parser = new DOMParser();
		InputStream is = FileDealor.class.getClassLoader().getResourceAsStream(
				"src");
		InputStreamReader ff;
		ff = new InputStreamReader(is, "UTF-8");
		BufferedReader in = new BufferedReader(ff);
		parser.parse(new InputSource(in));
		Document doc = parser.getDocument();
		// 获得body节点，以此为根，计算其文本内容
		Node body = doc.getElementsByTagName("BODY").item(0);
		Pattern p = Pattern.compile("娱乐没有圈", Pattern.MULTILINE);
		//getAttrValueByTag(getNodeByPattern(body, "a", p),"href");
		parse(doc);
	}
}

class Outlink {
	String toUrl;
	String showText;

	public Outlink(String u, String s) {

	}
}